package com.csdj.t309springboot.kaoshi.controller;
import com.csdj.t309springboot.kaoshi.utils.PathUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
 * https://blog.csdn.net/YINLINNEVERG/article/details/80250945
 */
@Controller
public class FileUploadController {
    private Logger log = LoggerFactory.getLogger("test");

    @GetMapping("/upload")
    public String uploadByGet(){
        return "upload";
    }

    @GetMapping("/uploads")
    public String uploadsByGet(){
        return "uploads";
    }

    @PostMapping("/upload")
    public String uploadByPost(Model model,
                               @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try{
                String filePath=PathUtil.uploadPath+file.getOriginalFilename();
                log.info("filePath="+filePath);
                BufferedOutputStream out=new BufferedOutputStream(
                        new FileOutputStream(new File(filePath)));
                out.write(file.getBytes());
                out.flush();
                out.close();
                model.addAttribute("msg", "上传文件成功");
            }
            catch(Exception e){
                e.printStackTrace();
                model.addAttribute("msg", "上传文件失败："+e.getMessage());
            }
        }
        else{//文件上传失败的消息提示
            model.addAttribute("msg", "上传文件失败：文件为空");
        }
        return "upload";
    }

    @PostMapping("/uploads")
    public String uploadsByPost(Model model, HttpServletRequest request){
        List<MultipartFile> files=((MultipartHttpServletRequest)request).getFiles("file");
        for(MultipartFile file:files){
            if (!file.isEmpty()) {
                try{
                    String filePath= PathUtil.uploadPath+file.getOriginalFilename();
                    BufferedOutputStream out=new BufferedOutputStream(
                            new FileOutputStream(new File(filePath)));
                    out.write(file.getBytes());
                    out.flush();
                    out.close();
                    model.addAttribute("msg", "上传文件成功");
                }
                catch(Exception e){
                    e.printStackTrace();
                    model.addAttribute("msg", "上传文件失败："+e.getMessage());
                }
            }
            else{
                model.addAttribute("msg", "上传文件失败：文件为空");
            }
        }

        return "uploads";
    }










//    /**
//     * 一定要是GetMapping
//     * @return
//     */
//    @GetMapping("/toUpload")
//    public String toUpload(){
//        System.out.println("正在前往toUpload");
//        //跳转视图
//        return "manager/upload/toUpload";
//    }
//    /**
//     * 接收多文件上传
//     * @param files
//     * @return
//     * @throws IOException
//     */
//    @PostMapping("/doUpload")
//    public String doUpload( MultipartFile[] files /*,
//                            @RequestParam String name,
//                            @RequestParam int age*/ ) throws IOException {
//        System.err.println("doUpload()");
//        for (MultipartFile file:files ) {
//            final String fileName1 = file.getName();
//            //System.out.println("size"+file.getSize());
//            //获取 原始文件的名字
//            String fileName = file.getOriginalFilename();//错误方式 : file.getName();
//            System.out.println("fileName = "+fileName);
//            //System.out.println("name="+ fileName.substring(fileName.lastIndexOf(".")) );
//            String ext = fileName.substring(fileName.lastIndexOf("."));
//
//            long curTime = System.currentTimeMillis();
//            System.out.println("curTime = "+curTime);
//            Path path = Paths.get("d:", "upload"+ext);
//            System.out.println("path = "+path);
//            //创建文件夹
//            if(!Files.exists(path)){
//                Files.createDirectory(path);
//            }
//
//            //String fileNewName = File.separator+"upload"+File.separator+curTime+ext;
//            //file.transferTo(Paths.get("/","upload",fileName));
//            //upload文件需要手动创建(代码创建 : file.mkdir())//最后那里是逗号,不是加号+
//            file.transferTo(Paths.get("d:","upload",String.valueOf(curTime)+ext));;
//        }
//
//        //跳转视图
//        return "WEB-INF/jsp/success";
//    }

//    /**
//     * 接收单文件上传
//     * @param file
//     * @return
//     * @throws IOException
//     */
//    @PostMapping("/doUpload")
//    public String doUpload(MultipartFile file) throws IOException {
//        //System.out.println("size"+file.getSize());
//        //获取 原始文件的名字
//        String fileName = file.getOriginalFilename();//错误方式 : file.getName();
//        System.out.println("fileName = "+fileName);
//        //System.out.println("name="+ fileName.substring(fileName.lastIndexOf(".")) );
//        String ext = fileName.substring(fileName.lastIndexOf("."));
//
//        long curTime = System.currentTimeMillis();
//        System.out.println("curTime = "+curTime);
//        Path path = Paths.get("d:", "upload"+ext);
//        System.out.println("path = "+path);
//        //创建文件夹
//        if(!Files.exists(path)){
//            Files.createDirectory(path);
//        }
//
//        //String fileNewName = File.separator+"upload"+File.separator+curTime+ext;
//        //file.transferTo(Paths.get("/","upload",fileName));
//        //upload文件需要手动创建(代码创建 : file.mkdir())//最后那里是逗号,不是加号+
//        file.transferTo(Paths.get("d:","upload",String.valueOf(curTime)+ext));;
//        //跳转视图
//        return "WEB-INF/jsp/success";
//    }

}
